import type { NextRequest, NextResponse } from 'next/server';
import { nanoid } from 'nanoid';
import { SignJWT, jwtVerify } from 'jose';
import { USER_TOKEN, getJwtSecretKey, expirationTime } from './constants';

interface UserJwtPayload {
  jti: string;
  iat: number;
}

export class AuthError extends Error {}

export async function verifyAuth(req: NextRequest) {
  // const token = req.headers.get('authorization');
  const token = req.cookies.get(USER_TOKEN)?.value;

  if (!token) throw new AuthError('Missing user token');

  try {
    const verified = await jwtVerify(token, new TextEncoder().encode(getJwtSecretKey()));
    return verified.payload as UserJwtPayload;
  } catch (err) {
    throw new AuthError('token 过期');
  }
}

// 解析token
export async function analysisToken(token: string) {
  try {
    const verified = await jwtVerify(token, new TextEncoder().encode(getJwtSecretKey()));
    return verified.payload || {};
  } catch (err) {
    throw new AuthError('token 解析失败');
  }
}

// 解析token返回全量数据
export async function analysisToken2(token: string) {
  try {
    const verified: any = await jwtVerify(token, new TextEncoder().encode(getJwtSecretKey()));
    const { personName, personId } = verified.payload;
    return {
      personName,
      personId,
    };
  } catch (err) {
    throw new AuthError('token 解析失败');
  }
}

export async function setUserCookie(data) {
  const token = await new SignJWT(data).setProtectedHeader({ alg: 'HS256' }).setJti(nanoid()).setIssuedAt().setExpirationTime(expirationTime).sign(new TextEncoder().encode(getJwtSecretKey()));
  return token;
}

export function expireUserCookie(res: NextResponse) {
  res.cookies.set(USER_TOKEN, '', { httpOnly: true, maxAge: 0 });
}
